<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="账号类型" prop="accountType">
            <el-select v-model="queryParams.accountType" placeholder="请选择账号类型" clearable style="width: 240px">
              <el-option v-for="dict in biz_account_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="账号标识" prop="accountKey">
            <el-input v-model="queryParams.accountKey" placeholder="请输入账号标识" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="账号名称" prop="accountName">
            <el-input v-model="queryParams.accountName" placeholder="请输入账号名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="支付方式" prop="paymentWay">
            <el-select v-model="queryParams.paymentWay" placeholder="支付方式" clearable style="width: 240px">
              <el-option v-for="dict in biz_payment_way" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['shop:cashier:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Upload" @click="handleImport" v-hasPermi="['shop:cashier:import']">导入</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="shopCashierList" class="tableEmpty">
        <el-table-column label="店铺ID" align="center" prop="shopId" width="180px"/>
        <el-table-column label="账号类型" align="center" prop="accountType">
        </el-table-column>
        <el-table-column label="账号标识" align="center" prop="accountKey" />
        <el-table-column label="账号名称" align="center" prop="accountName" />
        <el-table-column label="支付方式" align="center" prop="paymentWay">
          <template #default="scope">
            <dict-tag :options="biz_payment_way" :value="scope.row.paymentWay" />
          </template>
        </el-table-column>
        <el-table-column label="支付地址" align="center" prop="paymentLink">
          <template #default="scope">
            {{ scope.row.paymentLink==null?"--":scope.row.paymentLink}}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['shop:cashier:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['shop:cashier:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改商店收银员对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="shopCashierFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="账号类型" prop="accountKey">
          <el-select v-model="form.accountType" placeholder="请选择账号类型" clearable style="width: 240px">
            <el-option v-for="dict in biz_account_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号标识" prop="accountKey">
          <el-input v-model="form.accountKey" placeholder="请输入账号标识" />
        </el-form-item>
        <el-form-item label="账号名称" prop="accountName">
          <el-input v-model="form.accountName" placeholder="请输入账号名称" />
        </el-form-item>
        <el-form-item label="支付方式" prop="product">
          <el-select v-model="form.product" placeholder="支付方式" clearable style="width: 240px">
            <el-option v-for="dict in biz_payment_way" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付地址" prop="paymentLink">
          <el-input v-model="form.paymentLink" placeholder="请输入支付地址" />
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="form.id==undefined">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">
              {{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="导入收银账号" v-model="impDialog.visible" width="500px" append-to-body>
      <el-form ref="uploadFormRef" :model="uploadForm" label-width="120px">
        <el-form-item label="账号类型" prop="accountType">
          <el-select v-model="uploadForm.accountType" placeholder="请选择账号类型" clearable style="width: 240px">
            <el-option v-for="dict in biz_account_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        drag
        v-model:file-list="fileList"
        :data="uploadForm"
        :on-success="importSuccess"
        :action="uploadUrl"
        :auto-upload="false"
        :disabled="uploadLoading"
        :headers="uploadHeaders"
        name="cashierFile"
        accept=".xls, .xlsx"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          Drop file here or <em>click to upload</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            xls/xlsx files with a size less than 500kb
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button :disabled="uploadLoading" :loading="buttonLoading" type="primary" @click="submitImport">上 传</el-button>
          <el-button @click="cancelImport">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ShopCashier" lang="ts">
import { getToken } from '@/utils/auth'
import { UploadFilled } from '@element-plus/icons-vue'
import { listShopCashier, getShopCashier, addShopCashier, updateShopCashier, delShopCashier,changeCashierStatus } from '@/api/shop/cashier';
import { ShopCashierVO, ShopCashierQuery, ShopCashierForm } from '@/api/retail/shopCashier/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable,biz_payment_way,biz_account_type } = toRefs<any>(proxy?.useDict('sys_normal_disable','biz_payment_way','biz_account_type'));

const shopCashierList = ref<ShopCashierVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadUrl = baseUrl + "/shop/cashier/import";
const uploadLoading = ref(false);
const uploadFormRef = ref();
const uploadRef = ref();
const uploadHeaders = ref();
const fileList = ref([]);

const queryFormRef = ref<ElFormInstance>();
const shopCashierFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const impDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const uploadForm = ref({
  accountType: ''
})

const initFormData: ShopCashierForm = {
  id: undefined,
  shopId: undefined,
  accountKey: undefined,
  accountName: undefined,
  product: undefined,
  paymentLink: undefined,
  status: "0",
}
const data = reactive<PageData<ShopCashierForm, ShopCashierQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shopId: undefined,
    accountKey: undefined,
    accountName: undefined,
    product: undefined,
    paymentLink: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    shopId: [
      { required: true, message: "店铺ID不能为空", trigger: "blur" }
    ],
    accountKey: [
      { required: true, message: "账号标识不能为空", trigger: "blur" }
    ],
    accountName: [
      { required: true, message: "账号名称不能为空", trigger: "blur" }
    ],
    product: [
      { required: true, message: "支付方式不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商店收银员列表 */
const getList = async () => {
  loading.value = true;
  const res = await listShopCashier(queryParams.value);
  shopCashierList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  shopCashierFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加店铺收银员";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ShopCashierVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getShopCashier(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改店铺收银员";
}
/** 删除按钮操作 */
const handleDelete = async (row?: ShopCashierVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除收银员("' + row?.accountName + '")以及关联的收银码？').finally(() => loading.value = false);
  await delShopCashier(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}
/** 提交按钮 */
const submitForm = () => {
  shopCashierFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateShopCashier(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addShopCashier(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

const submitImport = () => {
  if(fileList.value.length == 0) {
    proxy?.$modal.msgError("请选择文件");
    return
  }
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getToken(),
    Clientid: import.meta.env.VITE_APP_CLIENT_ID
  }
  uploadLoading.value = true;
  uploadRef.value!.submit();
}
/** 导入提交后 */
const importSuccess = (response: any) => {

  uploadLoading.value = false;
  if(response.code==200) {
    proxy?.$modal.msgSuccess("上传成功");
  }else {
    proxy?.$modal.msgError("上传失败："+response.msg);
  }
}

/** 导入按钮操作 */
const handleImport = () => {
  impDialog.visible = true;
}
/** 取消导入*/
const cancelImport = () => {
  fileList.value = [];
  impDialog.visible = false;
  uploadFormRef.value?.resetFields();
}

// 状态修改
const handleStatusChange = async (row: ShopCashierVO) => {
  let text = row.status === 0 ? "启用" : "停用";
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.accountName + '"账号吗？');
    await changeCashierStatus(row.id, row.status);
    proxy?.$modal.msgSuccess(text + "成功");
  } catch {
    row.status = row.status === 0 ? 1 : 0;
  }
}

onMounted(() => {
  getList();
});
</script>
